package com.tone.ji_volunteer.aspect;

import com.alibaba.fastjson.JSONObject;
import com.tone.ji_volunteer.mapper.LogMapper;
import com.tone.ji_volunteer.mapper.UserMapper;
import com.tone.ji_volunteer.pojo.OperateLog;
import com.tone.ji_volunteer.util.JWT;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @author tone(ang)
 * version 1.0
 */
@Component
@Aspect
@Slf4j
public class LogAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private LogMapper logMapper;
    @Autowired
    private UserMapper userMapper;

    @Around("@annotation(com.tone.ji_volunteer.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable{
        //操作人ID - 当前登录员工ID
        //获取请求头中的jwt令牌, 解析令牌
        String token = request.getHeader("Authorization");
        String openid = (String) JWT.parseJwt(token).get("openid");
        Integer userId = userMapper.select(openid).getId();
        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        //操作类名
        String className = joinPoint.getTarget().getClass().getName();
        //操作方法名
        String methodName = joinPoint.getSignature().getName();
        //操作方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        long begin = System.currentTimeMillis();
        //返回值
        Object result = joinPoint.proceed();
        //方法返回值
        String returnValue = JSONObject.toJSONString(result);
        long end =  System.currentTimeMillis();
        OperateLog operateLog = new OperateLog(null, userId, operateTime, className, methodName, methodParams, returnValue, (end - begin));
        logMapper.insertLog(operateLog);
        return result;
    }
}
